<template>
  <div class="container">
    <Topnav title="编辑资料" @click="history" />
    <div class="containerB">
      <van-uploader :after-read="afterRead">
        <img
          v-if="userInfo.head_img !== ''"
          :src="$axios.defaults.baseURL + userInfo.head_img"
          alt=""
        />
        <img v-else src="@/assets/base-splash.jpg" alt="" />
      </van-uploader>
    </div>
    <Linex
      linetextL="昵称"
      :linetextR="userInfo.nickname"
      @click.native="isShowNickname = true"
    />
    <Linex
      linetextL="密码"
      linetextR="******"
      @click.native="isShowPwd = true"
    />
    <Linex
      linetextL="性别"
      :linetextR="userInfo.gender === 1 ? '小哥哥' : '小姐姐'"
      @click.native="isShowGender = true"
    />
    <van-dialog
      v-model="isShowNickname"
      show-cancel-button
      title="修改用户名"
      @confirm="setNickname"
    >
      <van-field v-model="newNickname" placeholder="请输入用户名"></van-field>
    </van-dialog>
    <van-dialog
      v-model="isShowPwd"
      show-cancel-button
      title="修改密码"
      @confirm="setPwd"
    >
      <van-field v-model="newPwd" placeholder="请输入密码"></van-field>
    </van-dialog>
    <van-action-sheet
      v-model="isShowGender"
      :actions="genderlist"
      @select="Setgender"
      cancel-text="取消"
    />
  </div>
</template>

<script>
import Linex from "../../components/Linex.vue";
import Topnav from "../../components/Topnav";
export default {
  components: {
    Linex,
    Topnav,
  },
  data() {
    return {
      userInfo: {},
      isShowNickname: false,
      isShowPwd: false,
      newNickname: "",
      newPwd: "",
      isShowGender: false,
      genderlist: [
        { name: "男", grender: 1 },
        { name: "女", gender: 0 },
      ],
    };
  },
  //生命周期钩子函数
  //created ：处于loading结束后，还做一些初始化，实现函数自执行（data数据已经初始化，但是DOM结构渲染完成，组件没有加载）
  created() {
    //进来首先渲染一遍,等修改昵称或者头像的时候需要再渲染这样不需要每次都刷新
    this.loadPage();
  },
  methods: {
    Setgender(action) {
      console.log("选一个选项");
      console.log(action);
      // console.log("选中了一个性别");
      const data = {
        gender: action.gender,
      };
      this.editProfile(data);
      this.isShowGender = false;
    },
    editProfile(data) {
      this.$axios({
        method: "post",
        url: "/user_update/" + localStorage.getItem("userId"),
        // headers: {
        //   Authorization: localStorage.getItem("token"),
        // },
        data,
      }).then((res) => {
        console.log(res.data);
        this.loadPage();
      });
    },
    //登录验证
    loadPage() {
      this.$axios({
        url: "/user/" + localStorage.getItem("userId"),
        // headers: {
        //   Authorization: localStorage.getItem("token"),
        // },
      }).then((res) => {
        console.log(res);
        if (res.data.message === "获取成功") {
          this.$toast("验证成功");
          this.userInfo = res.data.data;
          console.log(this.userInfo);
        } else {
          console.log("验证失败,请先登录");
          this.$router.push("/login");
        }
      });
    },
    history() {
      window.history.go(-1);
    },
    setPwd() {
      const data = {
        password: this.newPwd,
      };
      this.setU(data);
      this.newPwd = "";
    },
    setNickname() {
      const data = {
        nickname: this.newNickname,
      };
      this.setU(data);
      this.newNickname = "";
    },
    setU(data) {
      //每当我点击了输入框的时候我都应该发一个请求,编辑用户参数除了username和Id都是可以改的,传过去
      this.$axios({
        method: "post",
        url: "/user_update/" + localStorage.getItem("userId"),
        // headers: {
        //   Authorization: localStorage.getItem("token"),
        // },
        data,
      }).then((res) => {
        //一定要再then里面渲染,因为是异步的.写在里面,等渲染成功后调用
        console.log(res.data);
        // this.newNickname=''
        this.loadPage();
      });
    },
    afterRead(fileobj) {
      console.log(fileobj);
      const ft = new FormData()
      ft.append('file',fileobj.file)
      this.$axios({
        method:'post',
        url:'/upload',
        // headers:{
        //   Authorization: localStorage.getItem("token"),
        // },
        data:ft
      }).then(res=>{
        console.log(res);
        console.log(res.data);
        const {data, message}=res.data
        if(message==='文件上传成功'){
          const newData={
            head_img:data.url
          }
          //调用并且传递一个传输请求,head_img的地址为data.url,第八行有调用info.head_img拼接地址
          this.editProfile(newData)
        }
      })
    },
  },
};
</script>

<style lang='less' scoped>
* {
  padding: 0;
  margin: 0;
}
.container {
  background-color: #f2f2f2;
  padding-left: 20/360 * 100vw;

  .containerB {
    height: 120/360 * 100vw;
    display: flex;
    align-items: center;
    justify-content: center;
    img {
      height: 70/360 * 100vw;
      width: 70/360 * 100vw;
      border-radius: 50%;
      object-fit: cover;
    }
  }
}
</style>